package P106_DynamicProxy;

import org.junit.Test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 动态代理可以使代理模式更加灵活
 */
public class DynamicProxy {
    //抽象主题角色
    interface Subject {
        public void request();
    }

    //具体主题角色
    class RealSubject implements DynamicProxy.Subject {

        @Override
        public void request() {
            System.out.println("什么都不做");
        }
    }

    class SubjectHandler implements InvocationHandler {

        //被代理的对象
        private Subject subject;

        public SubjectHandler(Subject subject) {
            this.subject = subject;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("预处理");
            Object invoke = method.invoke(subject, args);
            System.out.println("后处理");
            return invoke;
        }
    }

    @Test
    public void Test() {
        //具体主题角色,也就是被代理类
        Subject subject = new RealSubject();

        //代理实例的处理Handler
        InvocationHandler handler = new SubjectHandler(subject);

        //当前加载器
        ClassLoader classLoader = subject.getClass().getClassLoader();
        //动态代理
        Subject proxy = (Subject) Proxy.newProxyInstance(classLoader, subject.getClass().getInterfaces(), handler);

        proxy.request();
    }
}
